"""
视频生成业务逻辑模块
提供配额管理、状态处理等工具函数
"""

import logging
from typing import Dict, Any
from app.core.quota_manager import quota_manager

logger = logging.getLogger(__name__)


async def check_user_quota(user_id: int, params: Dict[str, Any]) -> Dict[str, Any]:
    """
    检查用户配额
    
    Args:
        user_id: 用户ID
        params: 生成参数，包含service_type、duration等
        
    Returns:
        包含can_proceed和message的字典
    """
    try:
        # 估算任务所需配额
        estimated_quotas = quota_manager.estimate_task_quotas(user_id, {
            'service_type': params.get('service_type', 'video_generation'),
            'duration': params.get('duration', 5),
            'aspect_ratio': params.get('aspect_ratio', '16:9'),
            'generation_type': params.get('generation_type', 'text_to_video'),
            'provider': 'jimeng_ai'
        })
        
        # 检查配额是否充足
        return quota_manager.check_multiple_quotas(user_id, estimated_quotas, False)
        
    except Exception as e:
        logger.error(f"配额检查失败: {str(e)}")
        return {"can_proceed": True, "message": "配额检查跳过"}


async def update_quota_usage(user_id: int, params: Dict[str, Any], cost: float):
    """
    更新用户配额使用量
    
    Args:
        user_id: 用户ID
        params: 生成参数 (当前未使用，预留扩展)
        cost: 本次消耗成本
    """
    try:
        # 更新各项配额使用量
        quota_updates = {
            "daily_requests": 1,
            "daily_cost": cost,
            "monthly_requests": 1,
            "monthly_cost": cost
        }
        
        for quota_type, amount in quota_updates.items():
            quota_manager.update_usage(user_id, quota_type, amount)
            
        logger.info(f"用户 {user_id} 配额使用量更新完成 - 成本: ${cost}")
        
    except Exception as e:
        logger.error(f"配额使用量更新失败: {str(e)}")


def get_status_message(status: str) -> str:
    """
    获取任务状态的中文描述
    
    Args:
        status: 任务状态
        
    Returns:
        中文状态描述
    """
    status_messages = {
        "queued": "任务已提交，等待处理",
        "processing": "正在处理中，请耐心等待",
        "image_processing": "图片处理中",
        "video_processing": "视频生成中",
        "completed": "处理完成",
        "failed": "处理失败",
        "not_found": "任务未找到或已过期",
        "expired": "任务已过期"
    }
    return status_messages.get(status, f"状态未知: {status}")


def prepare_generation_params(request_data: Dict[str, Any]) -> Dict[str, Any]:
    """
    准备生成参数，统一参数格式和默认值
    
    Args:
        request_data: 请求数据
        
    Returns:
        处理后的参数字典
    """
    # 处理宽高比映射
    aspect_ratio_mapping = {
        "1:1": "1:1",
        "4:3": "4:3", 
        "3:2": "3:2",
        "16:9": "16:9",
        "21:9": "21:9",
        "3:4": "3:4",
        "9:16": "9:16"
    }
    
    params = {
        "duration": request_data.get("duration", 5),
        "aspect_ratio": aspect_ratio_mapping.get(
            request_data.get("aspect_ratio", "16:9"), 
            "16:9"
        ),
        "resolution": request_data.get("resolution", "720p"),
        "style": request_data.get("style", "realistic"),
        "seed": request_data.get("seed") if request_data.get("seed", -1) != -1 else None
    }
    
    # 判断生成类型
    if request_data.get("source_image_url") or request_data.get("source_image_base64"):
        params["generation_type"] = "image_to_video"
        params["image_strength"] = request_data.get("image_strength", 0.8)
    elif (request_data.get("template_image_url") and 
          request_data.get("user_image_url")):
        params["generation_type"] = "template_to_video_combined"
        params["fusion_strength"] = request_data.get("fusion_strength", 0.6)
        params["image_strength"] = request_data.get("image_strength", 0.8)
    else:
        params["generation_type"] = "text_to_video"
    
    return params